package com.springboot_experiment_2.config.CustomThreadPoolConfiguration;

import com.springboot_experiment_2.config.NoticeListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 自定义线程池
 *
 * @author:HGF
 */
@Configuration
@EnableConfigurationProperties(CustomPoolProperty.class)
public class CustomTaskExecutor {

    private static final Logger logger = LoggerFactory.getLogger(NoticeListener.class);

    @Autowired
    CustomPoolProperty poolProperty;

    /**
     * 自定义线程池
     */
    @Bean(name = {TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME,
            AsyncAnnotationBeanPostProcessor.DEFAULT_TASK_EXECUTOR_BEAN_NAME})
    public ThreadPoolTaskExecutor taskExecutor() {
        logger.info("自定义线程池");
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        // 核心线程池大小
        threadPoolTaskExecutor.setCorePoolSize(poolProperty.getCorePoolSize());
        // 最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(poolProperty.getMaxPoolSize());
        // 任务队列容量（阻塞队列）
        threadPoolTaskExecutor.setQueueCapacity(poolProperty.getQueueCapacity());
        // 空闲线程的存活时间
        threadPoolTaskExecutor.setKeepAliveSeconds(poolProperty.getKeepAliveSeconds());
        // 线程名称前缀
        threadPoolTaskExecutor.setThreadNamePrefix(poolProperty.getThreadNamePrefix());
        // 任务拒绝处理器
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }

}
